import React from 'react'
import {Editor, EditorState} from "react-draft-wysiwyg";
import styles from "./Editor.less";
import draft from "draft-js";
import draftToHtml from "draftjs-to-html";
import store from "store";
import api from '../../services/api'
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

const {ContentState} = draft
const {createAdminContentImage} = api

class DraftEditor extends React.PureComponent{
  constructor(props) {
    super(props);
    if(this.props.value != null && this.props.value != "") {
      let content = draft.EditorState.createWithContent(ContentState.createFromBlockArray(draft.convertFromHTML(this.props.value)));
      this.state = {editorState: content}
    } else {
      this.state = {editorState: draft.EditorState.createEmpty()};
    }
    this.editorValue = ""
  }

  onEditorStateChange = (editorState) => {
    console.log(editorState)
    const {onChange} = this.props
    this.setState({editorState})
  }

  /**
   * 编辑框内容变动
   *
   * @param rawContent
   */
  onValueChange = (rawContent) => {
    const {onChange} = this.props
    this.editorValue = draftToHtml(rawContent)
    onChange(this.editorValue)
  }

  upload = (file) => {
    let token = store.get('token')
    return new Promise(
      (resolve, reject) => {
        let formData = new FormData()
        formData.append('thumbnail', file)
        fetch(createAdminContentImage, {
          method: 'POST',
          headers: {
            'Authorization': token
          },
          body: formData,
        }).then(res => {
          return res.json()
        }).then(res => {
          if (res.code !== 2000) {
           // message.error('图片上传失败', 2)
            reject(res)
          } else {
            resolve({data: {link: res.payload}})
          }

        }).catch(err => {
          reject(err)
        })
      })
  }

  render() {
    let options = this.props
    let editorClass = this.editorClassName
    if(editorClass == null) {
      editorClass = styles.editor
    }

    return  <Editor
        editorState={this.props.value == this.editorValue ? this.state.editorState : draft.EditorState.createWithContent(ContentState.createFromBlockArray(draft.convertFromHTML(this.props.value || "")))}
        toolbarClassName={styles.toolbar}
        wrapperClassName={styles.wrapper}
        editorClassName={editorClass}
        onEditorStateChange={this.onEditorStateChange}

        {...options}
        onChange={this.onValueChange}
        toolbar={{
          image: {
            urlEnabled: true,
            uploadEnabled: true,
            alignmentEnabled: true,   // 是否显示排列按钮 相当于text-align
            uploadCallback: this.upload,
            previewImage: true,
            inputAccept: 'image/*',
            alt: {present: false, mandatory: false,previewImage: true}
          },
        }}
      />;
    }
}


export default DraftEditor
